package org.jeecg.common.util;

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.filter.FileTypeFilter;
import org.jeecg.common.util.filter.StrAttackFilter;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.net.URLDecoder;

/**
 * minio文件上传工具类
 */
@Slf4j
public class MinioUtil {
    private static String minioUrl;
    private static String minioName;
    private static String minioPass;
    private static String bucketName;

    public static void setMinioUrl(String minioUrl) {
        MinioUtil.minioUrl = minioUrl;
    }

    public static void setMinioName(String minioName) {
        MinioUtil.minioName = minioName;
    }

    public static void setMinioPass(String minioPass) {
        MinioUtil.minioPass = minioPass;
    }

    public static void setBucketName(String bucketName) {
        MinioUtil.bucketName = bucketName;
    }

    public static String getMinioUrl() {
        return minioUrl;
    }

    public static String getBucketName() {
        return bucketName;
    }

    private static MinioClient minioClient = null;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static String upload(MultipartFile file, String bizPath, String customBucket) {
        String file_url = "";
        // update-begin-author:国子软件 date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        bizPath = StrAttackFilter.filter(bizPath);
        // update-end-author:国子软件 date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        String newBucket = bucketName;
        if (oConvertUtils.isNotEmpty(customBucket)) {
            newBucket = customBucket;
        }
        try {
            System.out.println("minioUrl==========>" + minioUrl);
            initMinio(minioUrl, minioName, minioPass);
//            System.out.println("初始化完成"+minioName);
            // 检查存储桶是否已经存在
            if (minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) {
                log.info("Bucket already exists.");
            } else {
                // 创建一个名为ota的存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build());
                log.info("create a new bucket.");
            }
//            System.out.println("到了桶存不存在");
            // update-begin-author:国子软件 date:20210809 for: 过滤上传文件类型
            FileTypeFilter.fileTypeFilter(file);
            // update-end-author:国子软件 date:20210809 for: 过滤上传文件类型
            InputStream stream = file.getInputStream();
            // 获取文件名
            String orgName = file.getOriginalFilename();
            if ("".equals(orgName)) {
                orgName = file.getName();
            }
            orgName = CommonUtils.getFileName(orgName);
            String objectName = bizPath + "/"
                    + (orgName.indexOf(".") == -1
                    ? orgName + "_" + System.currentTimeMillis()
                    : orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."))
            );

            // 使用putObject上传一个本地文件到存储桶中。
            if (objectName.startsWith("/")) {
                objectName = objectName.substring(1);
            }
            System.out.println("objectName:" + objectName);
//            System.out.println("开始上传");
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
                    .bucket(newBucket)
                    .contentType("application/octet-stream")
                    .stream(stream, stream.available(), -1).build();
//            System.out.println("上传中"+objectArgs.toString());
            minioClient.putObject(objectArgs);
//            System.out.println("上传结束");
            stream.close();
            file_url = minioUrl + newBucket + "/" + objectName;
//            System.out.println("file_url====》"+file_url);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return file_url;
    }

    public static String uploadByCustom(MultipartFile file, String bizPath, String customBucket, String customName) {
        String file_url = "";
        // update-begin-author:国子软件 date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        bizPath = StrAttackFilter.filter(bizPath);
        // update-end-author:国子软件 date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
        String newBucket = bucketName;
        if (oConvertUtils.isNotEmpty(customBucket)) {
            newBucket = customBucket;
        }
        try {
            System.out.println("minioUrl==========>" + minioUrl);
            initMinio(minioUrl, minioName, minioPass);
//            System.out.println("初始化完成"+minioName);
            // 检查存储桶是否已经存在
            if (minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) {
                log.info("Bucket already exists.");
            } else {
                // 创建一个名为ota的存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build());
                log.info("create a new bucket.");
            }
//            System.out.println("到了桶存不存在");
            // update-begin-author:国子软件 date:20210809 for: 过滤上传文件类型
            FileTypeFilter.fileTypeFilter(file);
            // update-end-author:国子软件 date:20210809 for: 过滤上传文件类型
            InputStream stream = file.getInputStream();
            // 重新设置文件名
            // 获取文件后缀名
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."), filename.length());
            String objectName = bizPath + "/" + customName + "_" + System.currentTimeMillis() + suffix;
//
//            String objectName = bizPath+"/"
//                    +( customName.indexOf(".")==-1
//                    ?customName + "_" + System.currentTimeMillis()
//                    :customName.substring(0, customName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + customName.substring(customName.lastIndexOf("."))
//            );
            System.out.println("objectName:" + objectName);
            // 使用putObject上传一个本地文件到存储桶中。
            if (objectName.startsWith("/")) {
                objectName = objectName.substring(1);
            }
//            System.out.println("开始上传");
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
                    .bucket(newBucket)
                    .contentType("application/octet-stream")
                    .stream(stream, stream.available(), -1).build();
            minioClient.putObject(objectArgs);
//            System.out.println("上传结束");
            stream.close();
            file_url = minioUrl + newBucket + "/" + objectName;
//            System.out.println("file_url====》"+file_url);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return file_url;
    }

    /**
     * 文件上传
     *
     * @param file
     * @param bizPath
     * @return
     */
    public static String upload(MultipartFile file, String bizPath) {
        return upload(file, bizPath, null);
    }

    public static String uploadByCustomName(MultipartFile file, String bizPath, String customName) {
        return uploadByCustom(file, bizPath, null, customName);
    }

    /**
     * 文件上传
     *
     * @param file
     * @param bizPath
     * @return
     */
    public static String uploadByBucket(MultipartFile file, String bizPath, String customBucket) {
        return upload(file, bizPath, customBucket);
    }

    /**
     * 获取文件流
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    public static InputStream getMinioFile(String bucketName, String objectName) {
        InputStream inputStream = null;
        try {
            initMinio(minioUrl, minioName, minioPass);
            GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName)
                    .bucket(bucketName).build();
            inputStream = minioClient.getObject(objectArgs);
        } catch (Exception e) {
            log.info("文件获取失败" + e.getMessage());
        }
        return inputStream;
    }

    /**
     * 删除文件
     *
     * @param bucketName
     * @param objectName
     * @throws Exception
     */
    public static void removeObject(String bucketName, String objectName) {
        try {
            initMinio(minioUrl, minioName, minioPass);
            RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName)
                    .bucket(bucketName).build();
            minioClient.removeObject(objectArgs);
        } catch (Exception e) {
            log.info("文件删除失败" + e.getMessage());
        }
    }


    /**
     * @description: 删除文件夹
     * @author: 国子软件
     * @date: 2023/6/5 10:25
     * @param: bucketName 桶名
     * @param: objectName 文件夹名
     */
    public static void removeObjects(String bucketName, String objectName) {
        try {
            initMinio(minioUrl, minioName, minioPass);
            // 递归文件夹路径校验
            boolean bool = objectName.endsWith("/");
            String objectNames = objectName;
            if (!bool) {
                objectNames = objectName + "/";
            }
            // 文件夹下所有
            Iterable<Result<Item>> list = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(objectNames).recursive(false).build());
            for (Result<Item> item : list) {
                // 是否为文件
                String path = item.get().objectName();
                boolean b = path.endsWith("/");
                if (b) {
                    // 文件夹递归
                    removeObjects(bucketName, path);
                } else {
                    // 删除操作
                    minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(item.get().objectName()).build());
                }
            }
            // 出口
            return;
        } catch (Exception e) {
            log.info("文件删除失败" + e.getMessage());
        }
    }

    /**
     * 获取文件外链
     *
     * @param bucketName
     * @param objectName
     * @param expires
     * @return
     */
    public static String getObjectURL(String bucketName, String objectName, Integer expires) {
        initMinio(minioUrl, minioName, minioPass);
        try {
            // update-begin---author:国子软件  Date:20220121  for：获取文件外链报错提示method不能为空，导致文件下载和预览失败----
            GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName)
                    .bucket(bucketName)
                    .expiry(expires).method(Method.GET).build();
            // update-begin---author:国子软件  Date:20220121  for：获取文件外链报错提示method不能为空，导致文件下载和预览失败----
            String url = minioClient.getPresignedObjectUrl(objectArgs);
            return URLDecoder.decode(url, "UTF-8");
        } catch (Exception e) {
            log.info("文件路径获取失败" + e.getMessage());
        }
        return null;
    }

    /**
     * 初始化客户端
     *
     * @param minioUrl
     * @param minioName
     * @param minioPass
     * @return
     */
    private static MinioClient initMinio(String minioUrl, String minioName, String minioPass) {
        if (minioClient == null) {
            try {
                minioClient = MinioClient.builder()
                        .endpoint(minioUrl)
                        .credentials(minioName, minioPass)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return minioClient;
    }

    /**
     * 上传文件到minio
     *
     * @param stream
     * @param relativePath
     * @return
     */
    public static String upload(InputStream stream, String relativePath) throws Exception {
        initMinio(minioUrl, minioName, minioPass);
        if (minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            log.info("Bucket already exists.");
        } else {
            // 创建一个名为ota的存储桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            log.info("create a new bucket.");
        }
        PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath)
                .bucket(bucketName)
                .contentType("application/octet-stream")
                .stream(stream, stream.available(), -1).build();
        minioClient.putObject(objectArgs);
        stream.close();
        return minioUrl + bucketName + "/" + relativePath;
    }

    public static void main(String[] args) {
        File file = new File("D:\\3322.jpg");
        String fileName = file.getName();
        System.out.println(fileName);
        String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println(fileTyle);

//        String fileName = "3322";
//        System.out.println(fileName.indexOf(".")==-1);
//        System.out.println(fileName + "_" + System.currentTimeMillis());
//        System.out.println(fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf(".")));
        String objectName = "facelib/"
                + (fileName.indexOf(".") == -1
                ? fileName + "_" + System.currentTimeMillis()
                : fileName.substring(0, fileName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."))
        );
        System.out.println(objectName);
    }
}
